package lesson5.example3.transformer;

import java.io.ByteArrayInputStream;
import java.security.ProtectionDomain;
import java.util.stream.Collectors;

import org.apache.commons.lang.StringUtils;
import org.apache.logging.log4j.util.Strings;

import javassist.CtClass;
import lesson5.example5.ByteBuddyUtil;

public class ResetTransformer extends AbstractTransformer {
	public ResetTransformer(String fullClassName) {
		super(fullClassName);
	}
	public ResetTransformer() {
		super(null);
	}

	@Override
	public byte[] doTransform(
			ClassLoader loader, 
			String className, 
			Class<?> classBeingRedefined,
			ProtectionDomain protectionDomain, 
			byte[] classfileBuffer, 
			CtClass cc) throws Exception {
		if (!MAP.containsKey(className)) {
			return null;
		}
		
		ByteBuddyUtil.classPool.makeClass(new ByteArrayInputStream(MAP.get(className).bytes));
		
		MAP.remove(className);
		return null;
	}
	
	 public static String resetAllClasses() {
	      if (MAP.isEmpty()) {
	          return Strings.EMPTY;
	      }
	      
	      Class<?>[] classes = MAP.entrySet().stream()
	              .map(v -> v.getValue().clazz)
	              .collect(Collectors.toList())
	              .toArray(new Class<?>[MAP.size()]);
	      
	      String caches = StringUtils.join(MAP.keySet(), ",");
	      
	      ByteBuddyUtil.transformer(new ResetTransformer(), classes);
	      
	      MAP.clear();
	      return caches;
	  }
}